<template>
	<scroll-view scroll-y class="container flex-column">
		<view class="repair-text">
			<view class="repair-verify flex-row">
				<text class="symbol-size">{{symbol}}</text>
				<text class="fun-font-14px verify-text">{{repairname}}</text>
				<input placeholder="请输入姓名" v-model="rule.username" class="fun-font-14px input-text" />
			</view>
			<view class="repair-verify flex-row">
				<text class="symbol-size">{{symbol}}</text>
				<text class="fun-font-14px verify-text">{{phone}}</text>
				<input placeholder="请输入手机号" v-model="rule.phonenumber" class="fun-font-14px input-text" />
			</view>
			<view class="repair-verify-number flex-row">
				<text class="symbol-size">{{symbol}}</text>
				<text class="fun-font-14px verify-vtext">{{verifytext}}</text>
				<input placeholder="请输入验证码" v-model="rule.verify" class="fun-font-14px input-text" />
				<view class="v-btn">
					<button class="btn-box fun-img fun-font-12px " v-show="isgetCode" plain="flase" @click="verifybtn(rule)">获取验证码</button>
					<view v-show="!isgetCode" v-bind:class="{active:isActive}" class="bt-prepare ">
						<text v-show="isActive" @click="verifybtn(rule)">重新获取</text>
						<text v-show="!isActive" style="color: #888888;">{{count}}s后重新获取</text>
					</view>
				</view>
			</view>
		</view>
		<view class="repair-content flex-column flex-aligin-items-center">
			<view class="flex-row width-100 height-center">
				<text class="symbol-size">{{symbol}}</text>
				<text class="fun-font-14px context-text">{{repaircontent}}</text>
			</view>
			<textarea class="content-textarea fun-font-14px" maxlength="400" v-model="rule.areadesc" placeholder="输入报修内容"></textarea>
		</view>
		<view class="repair-msg flex-column">
			<view class="msg-text flex-column">
				<text class="fun-font-14px">{{rapairmsg}}</text>
				<text class="fun-font-14px width-100"  style="color: red;">请使用横屏拍照，以保证照片显示正确</text>
				<text class="fun-font-12px font-color-999">{{repairmsgs}}</text>
			</view>
		</view>
		<view class="msg-img width-95">
			<sunui-upbasic :upload_count="5" :upImgConfig="upImgBasic" @onUpImg="upBasicData" @onImgDel="delImgInfo" ref="uImage"></sunui-upbasic>
		</view>
		<view class="flex-center">
			<view class="repair-btn">
				<button class="fun-img btn-size fun-font-16px" @click="submit(rule)">{{submittext}}</button>
			</view>
		</view>
	</scroll-view>
</template>
<script>
	import sunuiUpbasic from '@/components/sunui-upimg/sunui-upbasic.vue'
	import {
		sendCode,
		verifyCode,
		createRepair
	} from '@/api/user/index.js'
	import {setUserInfoSync,getUserInfoSync} from '@/utils/store.js'
	import config from '@/utils/config.js'
	export default {
		components: {
			sunuiUpbasic
		},
		data() {
			return {
				// 基础版配置
				upImgBasic: {
					// 后端图片接口地址
					basicConfig: {
						url: config.BaseUrl + '/repair_user?action=UploadFile'
					},
					// 是否开启提示(提醒上传图片的数量)
					// tips: false,
					// 是否开启notli(开启的话就是选择完直接上传，关闭的话当count满足数量时才上传)
					notli: true,
					// 图片数量
					count: 5,
					// 相机来源(相机->camera,相册->album,两者都有->all,默认all)
					sourceType: 'all',
					// 是否压缩上传照片(仅小程序生效)
					sizeType: true,
					// 上传图片背景修改 
					upBgColor: '#EDEDED',
					// 上传icon图标颜色修改(仅限于iconfont)
					upIconColor: '#666',
					// 上传svg图标名称
					// upSvgIconName: 'icon-card',
					// 上传文字描述(仅限四个字)
					// upTextDesc: '上传证书',
					// 删除按钮位置(left,right,bleft,bright),默认右上角
					delBtnLocation: '',
					// 是否隐藏添加图片
					// isAddImage: false,
					// 是否隐藏删除图标
					// isDelIcon: false,
					// 删除图标定义背景颜色
					// delIconColor: '',
					// 删除图标字体颜色
					// delIconText: '',
					// 上传图标替换(+),是个http,https图片地址(https://www.playsort.cn/right.png)
					iconReplace: ''
				},
				symbol: '*',
				repairname: '姓名',
				rule: {
					equipment_id: this.$store.getters.getEquipmentInfo.id, //设备id
					phonenumber: '', //手机号
					username: '', //姓名
					areadesc: '', // 报修内容 
					verify: '', //输入的验证码
					file: [],
					engineer_id: '', //工程师id
					user_code: 0,
				},
				getcode: '',
				isgetCode: true,
				isActive: false,
				count: 0,
				phone: '手机号',
				verifytext: '验证码',
				repaircontent: '问题描述',
				rapairmsg: '上传资料和图片（清晰）',
				repairmsgs: '注：图片不得超过5张，提交后报修单将推给工程师',
				submittext: '提交'
			};
		},
		onLoad() {
			/* 获取缓存中的id 	this.$store.getters.getEquipmentInfo或this.$store.getters.getEquipmentInfo.engineer_id */
			this.rule.engineer_id = this.$store.getters.getEquipmentInfo.engineer_id
			this.echo()
		},
		methods: {
			/**
			 * 保存提交人信息,避免下次提交时需要重新输入
			 */
			echo(){
				this.rule.phonenumber = getUserInfoSync()?JSON.parse(getUserInfoSync()).phonenumber:''
				this.rule.username = getUserInfoSync()?JSON.parse(getUserInfoSync()).username:''
			},
			/* 倒计时 */
			verifybtn(rule) {
				let loginRules = [{
					name: 'phonenumber',
					required: true,
					type: 'phone',
					errmsg: '请输入正确的手机号'
				}]
				let valLoginRes = this.$validate.validate(this.rule, loginRules)
				if (!valLoginRes.isOk) {
					uni.showToast({
						icon: 'none',
						title: valLoginRes.errmsg
					});
				} else {
					this.isgetCode = false;
					if (!this.timer) {
						this.count = 60;
						this.isActive = false;
						this.timer = setInterval(() => {
							if (this.count > 0 && this.count <= 60) {
								this.count--;
							} else {
								this.isActive = true;
								clearInterval(this.timer);
								this.timer = null;
							}
						}, 1000);
					}
					sendCode(rule.phonenumber).then((res) => {
						this.getcode = res.result.code
						this.rule.user_code = res.result.code
						console.log(res)
					})
				}
			},
			/**
			 * 验证表单
			 */
			validate() {
				let loginRules = [{
						name: 'username',
						type: 'required',
						errmsg: '姓名不能为空'
					},
					{
						name: 'phonenumber',
						required: true,
						type: 'phone',
						errmsg: '请输入正确的手机号'
					},
					{
						name: 'verify',
						type: 'required',
						errmsg: '验证码不能为空'
					},
					{
						name: 'verify',
						type: 'lengthRange',
						min: 6,
						max: 6,
						errmsg: '请输入6位有效验证码'
					},
					{
						name: 'areadesc',
						type: 'required',
						errmsg: '故障描述不能为空'
					},

				]
				let valLoginRes = this.$validate.validate(this.rule, loginRules)
				if (!valLoginRes.isOk) {
					uni.showToast({
						icon: 'none',
						title: valLoginRes.errmsg
					});
					return false
				}
				return true
			},


			/**
			 * @param {Object} rule
			 * 创建维修单
			 */
			submit(rule) {
				uni.showLoading({
				    title: '加载中'
				});
				this.rule.file = this.rule.file.join().split(',')
				console.log(this.rule.file)
				if (this.validate()) {
					verifyCode(this.getcode, this.rule.verify).then((res) => {
						console.log(res)
						if (res.code === 1) {
							createRepair(this.rule).then((res) => {
								console.log(res)
								if (res.code === 1) {
									setUserInfoSync({phonenumber:this.rule.phonenumber,username:this.rule.username})
									this.$store.dispatch('setRpId', res.result.id)
									setTimeout(function () {
									   uni.hideLoading();
										 uni.showToast({
											title: '提交成功',
											icon:'success',
											duration: 1000,
											success: () => {
												setTimeout(()=>{
													uni.redirectTo({
														url: '/pages/index/maintain/maintain',
														})
												},1000)
												
											}
										 });
									}, 2000);
								}

							})
						}
					})
				}
			},
			// 删除图片 -2019/05/12(本地图片进行删除)
			async delImgInfo(e) {
				console.log('你删除的图片地址为:', e, this.rule.file.splice(e.index, 1));
			},
			// 基础版
			async upBasicData(e) {
				console.log('===>', e);
				// 上传图片数组
				let arrImg = [];
				for (let i = 0, len = e.length; i < len; i++) {
					try {
						if (e[i].path_server != "") {
							await arrImg.push(e[i].path_server.split(','));
						}
					} catch (err) {
						console.log('上传失败...');
					}
				}
				// 图片信息保存到data数组
				this.rule.file = arrImg;
				// 可以根据长度来判断图片是否上传成功. 2019/4/11新增
				if (arrImg.length == this.upImgBasic.count) {
					uni.showToast({
						title: `上传成功`,
						icon: 'none'
					});
				}
			}
		},
	}
</script>

<style lang="scss" scoped>
	.container {
		width: 100%;
		height: calc(100vh);
		background-color: #FFFFFF;

		.repair-text {
			width: 100%;
			height: 230rpx;
			background-color: #FFFFFF;
			border-bottom: 2rpx solid #f1f1f1;

			.repair-verify {
				width: 100%;
				height: 75rpx;
				border-bottom: 2rpx solid #f1f1f1;

				.symbol-size {
					width: 3%;
					padding-left: 20rpx;
					color: #e22018;
				}

				.verify-text {
					width: 15%;
					line-height: 75rpx;
				}

				.input-text {
					width: 80%;
					line-height: 75rpx;
				}
			}

			.repair-verify-number {
				width: 100%;
				height: 75rpx;

				.symbol-size {
					width: 3%;
					padding-left: 20rpx;
					color: #e22018;
				}

				.verify-vtext {
					width: 15%;
					line-height: 75rpx;
				}

				.input-text {
					width: 50%;
					line-height: 75rpx;
					text-indent: 20rpx;
				}

				.v-btn {
					text-align: center;
					width: 30%;
					height: 60rpx;
					color: #FFFFFF;

					.btn-box {
						width: 200rpx;
						color: #FFFFFF;
						background-color: #3CC51F;
						border: 0 solid #FFFFFF;
					}

					.bt-prepare {
						color: #000000;
						background-color: #FFF;
						line-height: 60rpx;
						font-size: 28rpx;
						text-align: center;
					}

					.active {
						color: #3cc51f;
						line-height: 60rpx;
						background-color: #FFFFFF;
					}
				}
			}
		}

		.repair-content {
			height: 280rpx;
			width: 100%;
			padding-top: 20rpx;
			padding-bottom: 10rpx;
			background-color: #FFFFFF;
			border-bottom: 2rpx solid #f1f1f1;

			.height-center {
				height: 50rpx;

				.symbol-size {
					width: 3%;
					height: 50rpx;
					padding-left: 20rpx;
					color: #e22018;
				}

				.context-text {
					width: 50%;
					height: 50rpx;
				}

			}

			.content-textarea {
				width: 95%;
				height: 220rpx;
				padding: 0 15rpx;
				background-color: #FFFFFF;

			}
		}

		.repair-msg {
			width: 100%;
			padding-top: 10rpx;
			background-color: #FFFFFF;

			.msg-text {
				width: 90%;
				padding-left: 20rpx;
			}

		}

		.msg-img {
			height: 400rpx;
			padding-left: 20rpx;
		}

		.repair-btn {
			margin-top: 20rpx;
			height: 100rpx;
			width: 90%;

			.btn-size {
				width: 100%;
				height: 75rpx;
				line-height: 75rpx;
				color: #FFFFFF;
				background-color: #3CC51F;
			}
		}
	}
</style>
